﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Pantry.Entity;
using Pantry.Business;
using Pantry.Commons;

namespace Pantry.Web.Users.Controls
{
    public partial class Region : System.Web.UI.UserControl
    {
        private readonly IFormatProvider _format = CultureInfo.CurrentCulture;
        private CountryBus _countryBus;
        private TrustRegionBus _trustRegionBus;
        private TrustRegion _trustRegion;
        protected void Page_Load(object sender, EventArgs e)
        {
            BindListContryToDropDown();
            if (!string.IsNullOrEmpty(Request.QueryString["TrustRegionId"]))
            {
                var trustRegionId = int.Parse(Request.QueryString["TrustRegionId"], _format);
                if (!IsPostBack)
                {
                    LoadTrustRegion(trustRegionId);
                }
            }
        }

        #region Methods
        /// <summary>
        /// Loads the trust region.
        /// </summary>
        /// <param name="trustRegionId">The trust region id.</param>
        private void LoadTrustRegion(int trustRegionId)
        {
            try
            {
                _trustRegionBus = new TrustRegionBus();
                _countryBus = new CountryBus();
                _trustRegion = _trustRegionBus.RetrieveTrustRegion(trustRegionId);
                if (_trustRegion != null)
                {
                    DropDownListCountry.SelectedValue = _trustRegion.CountryId.ToString(_format);
                    HiddenTrustRegionName.Value = _trustRegion.TrustRegionName;
                    TextBox1.Text = _trustRegion.TrustRegionName;
                    TextBoxDescription.Text = _trustRegion.Description;
                }
            }
            catch (ApplicationException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        /// <summary>
        /// Binds the list contry to drop down.
        /// </summary>
        private void BindListContryToDropDown()
        {
            try
            {
                _countryBus = new CountryBus();
                var tableContry = _countryBus.SelectAllCountry();
                DropDownListCountry.DataValueField = "CountryId";
                DropDownListCountry.DataTextField = "CountryName";
                DropDownListCountry.DataSource = tableContry;
                DropDownListCountry.DataBind();
            }
            catch (ArgumentException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        #endregion

        #region Event Handler
        /// <summary>
        /// Buttons the back click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonBackClick(object sender, EventArgs eventArgs)
        {
            Response.Redirect("ViewListTrustRegion.aspx");
        }
        /// <summary>
        /// Buttons the save click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonSaveClick(object sender, EventArgs eventArgs)
        {
            try
            {
                _trustRegionBus = new TrustRegionBus();
                _trustRegion = new TrustRegion
                                   {
                                       TrustRegionName = TextBox1.Text.Trim(),
                                       Description = TextBoxDescription.Text.Trim(),
                                       CountryId = int.Parse(DropDownListCountry.SelectedValue, _format)
                                   };
                var isExists = _trustRegionBus.CheckTrustRegionIsExists(_trustRegion.TrustRegionName);
                if (Request.QueryString["TrustRegionId"] != null)//Edit
                {
                    _trustRegion.TrustRegionId = int.Parse(Request.QueryString["TrustRegionId"], _format);
                    if (HiddenTrustRegionName.Value != TextBox1.Text)
                    {
                        if (!isExists)
                        {
                            var result = _trustRegionBus.UpdateTrustRegion(_trustRegion);
                            ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "MyKey",
                                                                                   result
                                                                                       ? "showmessage('Update trust region successfully !','SUCCESS','ViewListTrustRegion.aspx','true');"
                                                                                       : "showmessage('Update trust region failed !','ERROR','','false');",
                                                                                   true);
                        }
                        else
                        {
                            TextBox1.Focus();
                            ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "MyKey",
                                                                            "showmessage('Trust Region Name is already exists !','ERROR','','false');",
                                                                            true);
                        }
                    }
                    else
                    {
                        var result = _trustRegionBus.UpdateTrustRegion(_trustRegion);
                        ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "MyKey",
                                                                               result
                                                                                   ? "showmessage('Update trust region successfully !','SUCCESS','ViewListTrustRegion.aspx','true');"
                                                                                   : "showmessage('Update trust region failed !','ERROR','','false');",
                                                                               true);
                    }
                }
                else//Create
                {
                    if (!isExists)
                    {
                        var result = _trustRegionBus.CreateTrustRegion(_trustRegion);
                        ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "MyKey",
                                                                               result
                                                                                   ? "showmessage('Creating trust region successfully !','SUCCESS','','false');"
                                                                                   : "showmessage('Creating trust region failed !','ERROR','','false');",
                                                                               true);
                    }
                    else
                    {
                        TextBox1.Focus();
                        ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "MyKey",
                                                                        "showmessage('Trust Region Name is already exists !','ERROR','','false');",
                                                                        true);
                    }
                }
            }
            catch (ApplicationException ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
            }
        }
        /// <summary>
        /// Buttons the mark in active click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonMarkInActiveClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["TrustRegionId"]))
            {
                _trustRegionBus = new TrustRegionBus();
                var trustRegionId = int.Parse(Request.QueryString["TrustRegionId"], _format);
                bool result = _trustRegionBus.ChangeTrustRegionStatus(trustRegionId, false);
                if(result)
                {
                    Response.Redirect("ViewListTrustRegion.aspx");
                }

            }
            
        }
        #endregion
    }
}